import { RouteRecordRaw } from 'vue-router'
import { IBreadcrumb } from '@/base-ui/breadcrumb'
//返回菜单默认选中
let firstMenu: any = null
let firstRoute: RouteRecordRaw | undefined = undefined
export function menusToRoutes(roleMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  //读取所有route
  const allRoutes: RouteRecordRaw[] = []
  //webpack去读取所有main下的ts文件
  const routeFiles = require.context('../router/main', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    //key的数据是 ./xxx/xxx.ts,截取中间一段
    const route = require('../router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })

  //从上面的所有route中过滤出roleMenus匹配的routes
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url)
        if (route) routes.push(route)
        if (!firstRoute && !firstMenu) {
          //默认跳转页
          firstMenu = menu
          firstRoute = route
        }
      } else {
        _recurseGetRoute(menu.children)
      }
    }
  }
  _recurseGetRoute(roleMenus)

  return routes
}

//面包屑路径显示
export function pathMapBreadcrumbs(roleMenus: any[], currentPath: string) {
  const breadcrumbs: IBreadcrumb[] = []
  pathMapToMenu(roleMenus, currentPath, breadcrumbs)
  return breadcrumbs
}

export function pathMapToMenu(
  roleMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadcrumb[]
): any {
  for (const menu of roleMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name, path: '/' })
        breadcrumbs?.push({ name: findMenu.name, path: '/' })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}
//获取所有按钮的权限
export function menuMapToPermissions(roleMenus: any[]) {
  const permissions: string[] = []

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        permissions.push(menu.permission)
      }
    }
  }
  _recurseGetPermission(roleMenus)

  return permissions
}

export { firstMenu, firstRoute }
